package com.zl.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.zl.NotFoundException;
import com.zl.constants.constants;
import com.zl.constants.utils;
import com.zl.entity.dto.CommonResponseDto;
import com.zl.entity.po.TAutho;
import com.zl.entity.po.t_User;
import com.zl.entity.povo.User;
import com.zl.entity.vo.userVo;
import com.zl.mapper.TAuthoMapper;
import com.zl.service.UserService;
import com.zl.util.EmailUtil;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * @author zhanglei2
 */
@Controller
@RequestMapping("/admin")
@Log4j
public class UserLoginController {
    @Qualifier("userService")
    @Autowired
    private UserService userService;
    @Autowired
    private TAuthoMapper authoMapper;
    @GetMapping
    public String loginPage() {
        return "admin/reg";
    }

    /**
     * 用户注册
     * @return
     */
    @RequestMapping("/reg")
    public String regPage(){
        return "admin/reg";
    }
    @RequestMapping(value = "/userReg",method = RequestMethod.POST)
    public @ResponseBody CommonResponseDto userReg(@RequestBody String request,
                              HttpSession session,
                              RedirectAttributes attributes){
        t_User user = JSONObject.parseObject(request,t_User.class);
        if(StringUtils.isEmpty(user.getUsername()) && StringUtils.isEmpty(user.getPassword()) && StringUtils.isEmpty(user.getNickname())){
            session.setAttribute("massage","账号密码为空");
            return CommonResponseDto.builder().success(false).build();
        }

        //判断用户是否存在
        // Integer num = userService.getNumByUserName(user.getUsername());

        // t_User user = new t_User();
        // user.setUsername(username);
        // user.setPassword(password);
        // user.setNickname(nickname);
        if(!utils.isEmail(user.getEmail())){
            log.error("邮箱格式错误");
            throw new NotFoundException("邮箱格式错误");
        }
        t_User user1 = userService.regUser(user);
        User user2 = new User();
        BeanUtils.copyProperties(user1,user2);
        if (user2 != null) {
            user2.setPassword(null);
            session.setAttribute("user",user2);
            return CommonResponseDto.builder().data(user2).success(true).build();
        } else {
            attributes.addFlashAttribute("message", "注册失败");
            return CommonResponseDto.builder().success(false).build();
        }
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        t_User user = userService.checkUser(username, password);
        if(user==null){
            User user1 = null;
            return user(user1,session,attributes);
        }
        User user1 = new User();
        BeanUtils.copyProperties(user,user1);
       return user(user1,session,attributes);
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
    @PostMapping("/getUserNum")
    public @ResponseBody CommonResponseDto getUserNum(@RequestBody String username){
        // String name = JSONObject.parseObject(username,String.class);
        // String username = request.getParameter("username");
        // System.out.println(username+"============================");
        Integer num = userService.getNumByUserName(username);
        // System.out.println(num+"============================");
        // session.setAttribute("user",new t_User());//防止异步校验出现未登录重定向拦截
        return CommonResponseDto.builder().data(num).success(true).build();
    }
    @PostMapping("/sendPassword")
    public @ResponseBody CommonResponseDto sendPassWord(@RequestBody userVo userVo,HttpSession session){
        /**
         * 通过用户username+email来判断数据库用户是否唯一或者存在该用户
         * 不存在,或者不唯一,报错传错误信息\
         * 存在且唯一通过邮箱发送邮件,将密码发送给用户
         */
        List<t_User> list = userService.getNumByUserNameAndEmail(userVo);
        Integer num = list.size();
        if(num == 1){
            /**
             * 存在唯一的用户
             */
            try {
                EmailUtil.sendMail(list.get(0).getEmail(),list.get(0).getPassword());
            } catch (MessagingException e) {
                log.error("邮件发送异常{}",e);
                // session.setAttribute("message","邮箱错误或邮箱不存在");
                return CommonResponseDto.builder().code(constants.USER_FIND_PASSWORD_FAILED).data("邮箱错误或邮箱不存在").build();
            }
            // session.setAttribute("message","发送邮件成功,请耐心等待,接收邮件获取密码");
            return CommonResponseDto.builder().code(constants.USER_FIND_PASSWORD_SUCCESS).data("发送邮件成功,请耐心等待,接收邮件获取密码").build();
        }
        // session.setAttribute("message","用户数量异常");
        return CommonResponseDto.builder().code(constants.USER_NUM_FAILED).data("用户名或者邮箱不正确").build();
    }

    private String  user(User user,HttpSession session,RedirectAttributes attributes){
        if (user != null) {
            // 查看权限
            TAutho autho = authoMapper.selectByUserId(user.getId());
            user.setPassword(null);
            session.setAttribute("autho",autho);
            session.setAttribute("user",user);
            if(Objects.isNull(autho) || autho.getAuthoType().equals(constants.AUTHO_2)){
                return "redirect:/";
            }
            return "admin/index";
        } else {
            attributes.addFlashAttribute("message", "用户名和密码错误");
            return "redirect:/admin";
        }
    }
}
